<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="form" :inline="true">
            <el-form-item label="角色名称" class="item" prop="roleName">
                <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 240px"
                          @keyup.enter.native="load"/>
            </el-form-item>
            <el-form-item label="创建时间" class="item">
                <el-date-picker
                        v-model="dateRange"
                        style="width: 240px"
                        value-format="YYYY-MM-DD"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="load">搜索</el-button>
                <el-button icon="refresh" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <!--按钮区域    -->
        <div style="margin:5px">
            <el-button type="primary" plain icon="plus" @click="handleAdd">新增</el-button>
            <el-button type="success" plain icon="edit" :disabled="single" @click="handleUpdate">修改</el-button>

        </div>
        <!-- 列表区-->
        <el-table :data="tableData" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
                  @selection-change="handleSelectionChange" style="width: 100%">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="roleId" sortable label="ID"></el-table-column>
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column prop="roleCode" label="角色编码"></el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column fixed="right" label="操作" width="260">
                <template #default="scope">
                    <!--v-if="scope.row.userId !== 1"-->
                    <div>
                        <el-button type="text" icon="edit" @click="handleUpdate(scope.row)">修改</el-button>
                        <!-- 自带提示框的删除按钮 -->
                        <el-popconfirm title="确定删除吗？" @confirm="del(scope.row)">
                            <template #reference>
                                <el-button size="small" icon="delete" type="text">删除</el-button>
                                <!-- 注意此处如果方法加在删除按钮上，那么在弹出提示框点击确定的时候就无法执行删除操作了，所以这里需要将删除的方法，挂到弹框的确定按钮上 -->
                            </template>
                        </el-popconfirm>
                        <el-button type="text" plain icon="user" @click="handleAuthUser(scope.row)" >分配用户</el-button>
                    </div>
                </template>

            </el-table-column>
        </el-table>
        <!--列表分页-->
        <div style="margin: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"> //双引号里面的total是定义一个变量，在这里定义了，就需要在下面data里面初始化一下
            </el-pagination>
        </div>
        <!-- 新增角色弹窗 -->
        <el-dialog :title="title" v-model="dialogVisible" width="60%">
            <el-form :model="form" label-width="120px">
                <el-form-item label="角色名称" class="item">
                    <el-input v-model="form.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色编码" class="item">
                    <el-input v-model="form.roleCode"></el-input>
                </el-form-item>
                <el-form-item label="菜单权限" class="item">
                    <el-tree
                            class="tree-border"
                            :data="menuOptions"
                            show-checkbox
                            node-key="menuId"
                            ref="menuTree"
                            check-strictly: false
                            empty-text="加载中请稍候"
                            @check-change="handleChangeClick"
                            :props="{ label: 'menuName' , }">
                    </el-tree>
                </el-form-item>

            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
              </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import request from "@/utils/request";
    import qs from 'qs'
    import {ElMessage} from 'element-plus'
    import {addRole, delRole, getRole, roleList, updateRole} from "../../api/system/role";
    import {treeselect} from "../../api/system/menu";

    export default {
        name: 'role',
        components: {},
        data() {
            return {

                title: '',
                dialogVisible: false,
                total: 0,  //默认10条
                tableData: [],
                single: true,
                currentPage: 1,
                pageSize: 5,
                // 查询参数
                queryParams: {},
                form: {},
                dateRange: [],
                query: '',
                requestParams: {},
                menuOptions: [],
                item: {},
                roleId:""
            }
        },

        //页面加载完立即执行的方法
        mounted() {
            this.load()
        },

        methods: {
            //查询方法
            load() {
                let timeRange = {'beginTime': this.dateRange[0], 'endTime': this.dateRange[1]}
                const params={
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    roleName: this.queryParams.roleName,
                    params: timeRange
                }
                const data=qs.stringify(params)
                //axios中 get请求无法传递复杂json对象需要使用qs.stringify()对参数进行序列化
                roleList(data).then(res => {
                    this.tableData = res.data.list
                    this.total = res.data.total
                })
            },

            //打开新增的弹窗
            handleAdd() {
                this.title = '新增角色';
                //清空表单中的数据
                this.form = {};
                this.dialogVisible = true;
                request.get("/sys/menu/menuTree").then(res => {
                    this.menuOptions = res.data;
                });
            },

            /**
             * 选择节点
             */
            handleChangeClick() {
                let checkedKeys = this.$refs.menuTree.getCheckedKeys();
                // 半选中的菜单节点
                let halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys();

                checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);

                console.log("所有选中的节点数据"+checkedKeys)

                return checkedKeys;

            },


            //打开修改弹窗(和新增用的一个)
            async handleUpdate(row) {
                this.title = '修改角色';
                await menuList().then(res => {
                    this.menuOptions = res.data;
                    return res;
                });
                const roleId = row.roleId || this.ids;
                getRole(roleId).then(res => {
                        this.form = res.data;
                        let checkedKeys = res.data.menuIds
                        checkedKeys.forEach((v) => {
                            this.$nextTick(() => {
                                this.$refs.menuTree.setChecked(v, true, false);
                            })
                        })
                });
                this.dialogVisible = true;
            },

            //进行保存 使用aios进行数据交互
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.roleId) {
                            this.form.menuIds = this.handleChangeClick()
                            updateRole(this.form).then(res => {
                                ElMessage.success('修改成功');
                                this.load();  //更新完成后，重新刷新表格数据
                                this.dialogVisible = false;    //最后关闭弹窗
                            })
                        } else {
                            this.form.menuIds = this.handleChangeClick()
                            addRole(this.form).then(res => {
                                ElMessage.success('保存成功');
                                this.load();  //重新刷新表格数据
                                this.dialogVisible = false;    //最后关闭弹窗
                            })
                        }
                    }
                })

            },



            //分配用户
            handleAuthUser(row){
                const roleId = row.roleId
                this.item.path='/authuser/'+ roleId
                this.item.menuName="分配用户",
                this.$router.push({ name:'authuser', params:{roleId:roleId}})
                this.$store.commit('selectMenu', this.item)
            },

            del(row) {
                const roleIds = row.roleId || this.ids;
                delRole(roleIds).then(res => {
                    ElMessage.success(res.msg);
                    this.load()
                }).catch(() => {});

            },

            reset() {
                this.dateRange = [];
                this.$resetForm('form');
            },

            //在上面的data中，pageSize和currentPaage都有默认值，这里要触发分页，需要重新根据变量赋值
            //改变当前每页条数触发
            handleSizeChange(pageSize) {
                this.pageSize = pageSize
                this.load()
            },

            //改变当前页码触发
            handleCurrentChange(pageNum) {
                this.currentPage = pageNum
                this.load()
            },

            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.userId)
                this.single = selection.length != 1
            },


        }
    }
</script>

<style scoped>
    #app-container {
        padding: 15px;
    }

    /* tree border */
    .tree-border {
        margin-top: 5px;
        border: 1px solid #e5e6e7;
        background: #FFFFFF none;
        border-radius: 4px;
        width: 100%
    }
</style>
